import { defineComponent, onMounted, reactive, ref, toRefs, unref } from 'vue'
import { Card, Button, Table, Space, Row, Col, Input, message } from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useColumns } from '@/views/system/user/use-columns'
import UserDetail from './detail'
import UpdatePassword from './component/updatePassword'
import ImportUser from './component/importUser'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import { exportUser } from '@/api/system/user'

const User = defineComponent({
  name: 'User',
  setup() {
    const tableLoading = ref<boolean>(false)
    const importShow = reactive({
      show: false
    })
    const updatePassWordShow = reactive({
      show: false
    })
    const tableData = ref<any[]>([])
    const pageType = ref<BusinessPageTypeEnum>(BusinessPageTypeEnum.TABLE)
    const selectUser = reactive({
      userCode: null as string | null,
      username: null as string | null
    })
    const tableTotal = ref<any>({
      currPage: 1,
      totalCount: 0,
      totalPage: 0,
      pageSize: 10
    })
    const tableQuery = reactive({
      username: '',
      telephone: '',
      pageNum: 1,
      pageSize: 10
    })
    const { status, getUserList, updateUserStatusById, updateUserPasswordById } = useDetail()

    const updateUser = (userCode: string) => {
      pageType.value = BusinessPageTypeEnum.UPDATE
      selectUser.userCode = userCode
    }

    const detailUser = (userCode: string) => {
      pageType.value = BusinessPageTypeEnum.DETAIL
      selectUser.userCode = userCode
    }

    const updateUserPassword = (userCode: string, name: string) => {
      updatePassWordShow.show = true
      selectUser.username = name
      selectUser.userCode = userCode
    }

    const updateStatus = async (id: number, status: any) => {
      await updateUserStatusById(id, status)
      await fetchData()
    }

    const handlerUpdateUserPassword = async (id: number, password: string) => {
      await updateUserPasswordById(id, password)
      message.info('密码修改成功！')
      updatePassWordShow.show = false
    }

    const { getColumns, tableColumns } = useColumns(updateUser, detailUser, updateStatus, updateUserPassword)

    const onSearch = async () => {
      if (
        (!tableQuery.username || tableQuery.username === '') &&
        (!tableQuery.telephone || tableQuery.telephone === '')
      ) {
        message.warning('请输入要查询的员工姓名或者手机号！')
        return
      }
      tableQuery.pageNum = 1
      tableQuery.pageSize = 10
      await fetchData()
    }

    const onConfirmModal = () => {
      onCancelModal()
      onReset()
    }

    const onCancelModal = () => {
      pageType.value = BusinessPageTypeEnum.TABLE
      selectUser.userCode = null
      selectUser.username = null
    }

    const handlePageChange = async () => {
      await fetchData()
    }

    async function fetchData() {
      tableLoading.value = true
      try {
        const data = await getUserList(tableQuery)
        const { items, pageInfo } = data as unknown as any
        tableData.value = items
        tableTotal.value = pageInfo
        tableLoading.value = false
      } catch (error) {
        tableLoading.value = false
        console.log(error)
      }
    }

    const importData = () => {
      importShow.show = true
    }

    const onReset = async () => {
      tableQuery.pageNum = 1
      tableQuery.pageSize = 10
      tableQuery.username = ''
      tableQuery.telephone = ''
      await fetchData()
    }

    const addRole = () => {
      pageType.value = BusinessPageTypeEnum.ADD
    }

    const exportData = () => {
      exportUser(tableQuery)
        .then((res: any) => {
          debugger
          const blob = new Blob([res.data], { type: 'application/xlsx' })
          const filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = filename
          link.click()
          URL.revokeObjectURL(url)
          message.success('下载成功')
        })
        .catch(function (error: any) {
          console.log(error)
        })
    }

    onMounted(async () => {
      await fetchData()
    })

    return {
      ...toRefs(status),
      tableLoading,
      tableData,
      tableTotal,
      tableQuery,
      tableColumns,
      pageType,
      selectUser,
      updatePassWordShow,
      importShow,
      onSearch,
      onReset,
      handlePageChange,
      getColumns,
      addRole,
      onConfirmModal,
      onCancelModal,
      handlerUpdateUserPassword,
      importData,
      exportData
    }
  },

  render() {
    const {
      tableColumns,
      tableLoading,
      tableData,
      tableTotal,
      tableQuery,
      pageType,
      selectUser,
      updatePassWordShow,
      importShow,
      onSearch,
      onReset,
      getColumns,
      handlePageChange,
      addRole,
      onConfirmModal,
      onCancelModal,
      handlerUpdateUserPassword,
      importData,
      exportData
    } = this
    return (
      <>
        {pageType === BusinessPageTypeEnum.TABLE && (
          <>
            <Card>
              <Row gutter={16} align='middle' type='flex'>
                <Col span={18}>
                  <Space>
                    <span>员工姓名:</span>
                    <Input v-model={[tableQuery.username, 'value']} placeholder={'请输入'}></Input>
                  </Space>
                  <Space style={{ marginLeft: '10px' }}>
                    <span>手机号:</span>
                    <Input v-model={[tableQuery.telephone, 'value']} placeholder={'请输入'}></Input>
                  </Space>
                </Col>
                <Col span={6}>
                  <Space>
                    <Button type={'primary'} onClick={onSearch}>
                      查询
                    </Button>
                    <Button onClick={onReset}>重置</Button>
                  </Space>
                </Col>
              </Row>
              <div style={{ marginTop: '16px' }}>
                <Space>
                  <Button type={'primary'} onClick={addRole} v-auth={['sys:user:add']}>
                    +新增
                  </Button>
                  <Button type={'primary'} onClick={importData} v-auth={['sys:user:import']}>
                    批量导入
                  </Button>
                  <Button type={'primary'} onClick={exportData} v-auth={['sys:user:export']}>
                    批量导出
                  </Button>
                </Space>
              </div>
            </Card>
            <Card style={{ marginTop: '16px' }}>
              <Table
                rowKey='id'
                columns={tableColumns}
                dataSource={unref(tableData)}
                loading={unref(tableLoading)}
                pagination={{
                  current: tableQuery.pageNum,
                  pageSize: tableQuery.pageSize,
                  total: unref(tableTotal.totalCount),
                  showTotal: () => `Total ${unref(tableTotal.totalCount)} items`,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  onChange: handlePageChange,
                  'onUpdate:current': current => (tableQuery.pageNum = current),
                  'onUpdate:pageSize': pageSize => (tableQuery.pageSize = pageSize)
                }}
              >
                {{
                  bodyCell: ({ column, record }) => getColumns(column, record)
                }}
              </Table>
            </Card>
            {updatePassWordShow.show && (
              <UpdatePassword
                show={updatePassWordShow.show}
                userCode={selectUser.userCode}
                username={selectUser.username}
                onConfirmModal={handlerUpdateUserPassword}
                onCancelModal={() => (updatePassWordShow.show = !updatePassWordShow.show)}
              />
            )}
            {importShow.show && (
              <ImportUser show={importShow.show} onCancelModal={() => (importShow.show = !importShow.show)} />
            )}
          </>
        )}
        {pageType !== BusinessPageTypeEnum.TABLE && (
          <UserDetail
            userCode={selectUser.userCode}
            businessType={pageType}
            onCancelModal={onCancelModal}
            onConfirmModal={onConfirmModal}
          />
        )}
      </>
    )
  }
})
export default User
